<template>
  <ul>
    <li v-for="product in products">
      {{product.name}}: {{product.price}} x {{product.quantity}}
    </li>
  </ul>
  <div>
    总价：{{totalPrice}}
  </div>
</template>

<script>
export default {
  props: ['product'],

  data() {
    return {
      products: []
    }
  },

  computed: {
    totalPrice() {
      return this.products.reduce((total, p) => {
        total += p.price * p.quantity
        return total
      }, 0)
    }
  },

  watch: {
    product(p) {
      let product = this.products.find(v => v.id === p.id)
      if (product) {
        product.quantity++
      } else {
        let {id, name, price} = p
        this.products.push({
          id,
          name,
          price,
          quantity: 1
        })
      }
    }
  }
}
</script>

<style lang='stylus' scoped>

</style>